package Proxy.CjlibProxy;

import Proxy.DynamicProxy.Subject;
import net.sf.cglib.proxy.Enhancer;
import net.sf.cglib.proxy.MethodInterceptor;
import net.sf.cglib.proxy.MethodProxy;

import java.lang.reflect.Method;

/**
 * Created by svenl on 7/11/2017.
 */
public class CjlibProxy implements MethodInterceptor {

    private Subject subject;


    public CjlibProxy(Subject subject) {
        super();
        this.subject = subject;
    }

    public Subject createProxy() {
        // 使用CGLIB生成代理:
        // 1.声明增强类实例,用于生产代理类
        Enhancer enhancer = new Enhancer();
        // 2.设置被代理类字节码，CGLIB根据字节码生成被代理类的子类
        enhancer.setSuperclass(subject.getClass());
        // 3.//设置回调函数，即一个方法拦截
        enhancer.setCallback(this);
        // 4.创建代理:
        return (Subject) enhancer.create();
    }


    /**
     * 回调函数
     *
     * @param o           代理对象
     * @param method      委托类方法
     * @param args     方法参数
     * @param methodProxy 每个被代理的方法都对应一个MethodProxy对象，
     *                    methodProxy.invokeSuper方法最终调用委托类(目标类)的原始方法
     * @return
     * @throws Throwable
     */
    @Override
    public Object intercept(Object o, Method method, Object[] args, MethodProxy methodProxy) throws Throwable {

        System.out.println("hey, this is before intercept method");

        methodProxy.invokeSuper(o, args);
        System.out.println("hey,and this is after intercept method");
        return null;
    }
}
